package com.hsc.account;

import java.util.List;
import java.util.Map;

import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.internet.MimeMessage;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.hsc.db.tools.AccountList;
import com.hsc.db.tools.AccountService;
import com.hsc.db.tools.EmailService;
import com.hsc.db.tools.ItemList;
import com.hsc.db.tools.ItemService;
import com.hsc.db.tools.ReciveOneMail;
import com.hsc.db.tools.StringUtils;
import com.hsc.db.tools.UseItemService;
import com.hsc.db.tools.useitem;

public class recvMailTread extends Thread {

	private ItemService items;
	private AccountService accs;
	private Message[] message;
	private Context context;
	private Handler handler;
	private TextView  tzhichu;
	private UseItemService useServices;

	private  List<AccountList> cur;
	private ListView listView;
	private GridView dateview;

	public recvMailTread(ItemService items,Context context,Handler handler,TextView  tzhichu,ListView listView,GridView dateview)
	{
		this.items=items;
		this.accs=new AccountService(context);
		this.context=context;
		this.handler = handler;
		this.tzhichu = tzhichu;

		this.listView = listView;
		this.dateview = dateview;
		this.useServices= new UseItemService(context);
	}


	@Override
	public void run() {
		// 获取信息
		ItemList send = items.getlDataFlag("1");
		ItemList pwd = items.getlDataFlag("2");
		if(send!=null && pwd!=null)
		{
			message = EmailService.GetMessage("pop.163.com", send.getType(),
					pwd.getType());

			if(message !=null)
			{
				for(int i=0;i<message.length;i++)
				{
					ReciveOneMail pmm = new ReciveOneMail((MimeMessage) message[i]);

					MimeMessage mm = (MimeMessage) message[i];
					try {
						mm.setFlag(Flags.Flag.DELETED, true);
					} catch (MessagingException e) {
						e.printStackTrace();
					}

					if(pmm.getSubject().equals("<data>"))
					{
						/* 处理邮件正文 */
						pmm.getMailContent((Part)  message[i], context);


						String content = StringUtils.replaceBlank(pmm.getBodyText());

//						oneActivity.log("["+content+"]");

						if(content.indexOf("|")>0)
						{
							String[] arrItem=content.split("\\|");

							for(int k=0;k<arrItem.length;k++)
							{
								if(arrItem[k].indexOf(",")>0)
								{
									String[] data = arrItem[k].split(",");
//									oneActivity.log("["+data.length+"]");
//									oneActivity.log("["+data[0]+"]");
//									oneActivity.log("["+data[1]+"]");
//									oneActivity.log("["+data[2]+"]");
//									oneActivity.log("["+data[3]+"]");
//									oneActivity.log("["+data[4]+"]");
//									oneActivity.log("["+data[5]+"]");
//									oneActivity.log("["+data[6]+"]");
//									oneActivity.log("["+data[7]+"]");

									AccountList acc = new AccountList();
									acc.setDate(data[0]);
									acc.setAmt(Double.parseDouble(data[1]));
									acc.setBalance(Double.parseDouble(data[2]));
									acc.setType(data[3]);
									acc.setTime(data[4]);

									acc.setRemark(data[6]);

									if(data.length==8)
									{
										acc.setUse(data[7]);
									}

									if(data[5].equals("1"))
									{
											/*如果存在则修改记录*/
										if(	accs.getCountByRemark(acc) > 0 )
										{
//												oneActivity.log("["+"update"+"]");
											accs.updateBalance(acc, 3);
										}else
										{
//												oneActivity.log("["+"add"+"]");
											accs.save(acc);
										}

									}else
									{
										accs.deleteByRemark(data[6]);
									}
								}

							}
						}

					}else if(pmm.getSubject().equals("<item>"))
					{

						/* 处理邮件正文 */
						pmm.getMailContent((Part)  message[i], context);


						String content = StringUtils.replaceBlank(pmm.getBodyText());

						if(content.indexOf("|")>0)
						{
							String[] arrItem=content.split("\\|");

							for(int k=0;k<arrItem.length;k++)
							{
								if(arrItem[k].indexOf(",")>0)
								{
									String[] data = arrItem[k].split(",");

									useitem item = new useitem();
									item.setUsetype(data[0]);
									item.setFlag("3");

									if(data[1].equals("1"))
									{
											/*如果存在则修改记录*/
										if(	useServices.getItemByType(data[0]) > 0 )
										{
											useServices.updateFlag(data[0],"3");
										}else
										{
											useServices.save(item);
										}

									}else
									{
										useServices.deleteByType(data[0]);
									}
								}

							}
						}


					}

				}
				EmailService.freeMassage();

				//处理未上传的数据
				List<AccountList> list = accs.getScroolDataFailed();
				for(AccountList item :list){
					item.setId((int)(item.getBalance()));
				}
				if(list.size()>0)
				{
					sendEmailTread tread = new sendEmailTread(list, items,accs);
					tread.start();
				}

				//处理未上传分组数据
				List<useitem> itemlist = useServices.getDataFailed();

				if(itemlist.size()>0)
				{
					sendTypeThread tread = new sendTypeThread(itemlist,items);
					tread.start();
				}


				//刷新页面
				handler.post(new Runnable() {

					@Override
					public void run() {

						List<Map<String, Object>> list = oneActivity.getData(oneActivity.iyear,oneActivity.imonth);
						gridadapter sim_adapter = new gridadapter(context, list,oneActivity.imonth,oneActivity.curday);
						dateview.setAdapter(sim_adapter);

//							oneActivity.gv=-1;

						List<AccountList> cur1 = accs.getListData(oneActivity.iyear,oneActivity.imonth,oneActivity.curday);
						ListViewAdapter adapter = new ListViewAdapter(context,cur1,items);
						listView.setAdapter(adapter);

						tzhichu.setText(String.format("%.1f",accs.getZSum("1",oneActivity.iyear,oneActivity.imonth)));

					}
				});
			}
		}
	}



}
